package com.epam.weblibrary.service.book;

import com.epam.weblibrary.entities.book.Book;
import com.epam.weblibrary.repositories.book.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Iurii_Miedviediev on 9/11/2014.
 */
@Service
@Transactional(readOnly = true)
public class BookServiceImpl implements BookService {

    private static final int PER_PAGE = 9;

    @Autowired
    private BookRepository bookRepository;

    @Override
    public List<Book> findAll() {
        return bookRepository.findAll();
    }

    @Override
    public List<Book> findAllAvailable() {
        return bookRepository.findByAvailable(true);
    }

    @Override
    public Book find(Long id) {
        return bookRepository.findOne(id);
    }

    @Override
    public Book save(Book book) {
        return bookRepository.saveAndFlush(book);
    }

    @Override
    public void delete(Long id) {
        bookRepository.delete(id);
        bookRepository.flush();
    }

    @Override
    public Page<Book> getBookPage(Integer pageNumber) {
        PageRequest request =
                new PageRequest(pageNumber - 1, PER_PAGE, Sort.Direction.DESC, "title");
        return bookRepository.findByAvailable(true, request);
    }
}
